<script lang="ts" setup>
import flv from "flv.js";
import { ref, onMounted } from "vue";
import { invoke, convertFileSrc } from "@tauri-apps/api/tauri";

const player = ref();

onMounted(() => {
  greet();
});

const play = () => {
  player.value.play();
};

const pause = () => {
  player.value.pause();
};

// 获取视频
const videoUrlList = ref<Array<string>>([]);
async function greet() {
  videoUrlList.value = [];
  videoUrlList.value = await invoke("get_images", {
    path: "C:\\Users\\A\\Videos",
  });
  videoUrlList.value = videoUrlList.value.map((item) => {
    return convertFileSrc(item);
  });

  if (flv.isSupported()) {
    player.value = flv.createPlayer({
      type: "video/mp4",
      url: videoUrlList.value[0],
    });
  }

  const video = document.getElementById("myVideo");
  player.value.attachMediaElement(video);
  player.value.load();
  pause();
}

// 选择视频
const videoUrl = ref("");
const onChange = (value: string) => {
  if (player.value) {
    player.value.unload();
    player.value.detachMediaElement();
    player.value.destroy();
    player.value = null
  }

  player.value = flv.createPlayer({
      type: "video/mp4",
      url: value,
    });
  const video = document.getElementById("myVideo");
  player.value.attachMediaElement(video);
  player.value.load();
  pause();
};

</script>

<template>
  <div>
    <div class="flv-box">
      <div style="display: flex;">
        <t-button @click="play">播放</t-button>
        <t-button @click="pause">暂停</t-button>
        <t-select v-model="videoUrl" @change="onChange">
          <t-option
            v-for="(item, index) in videoUrlList"
            :key="index"
            :value="item"
          >
            {{ item }}
          </t-option>
        </t-select>
      </div>
      <video id="myVideo" controls autoplay muted></video>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.flv-box {
  width: 50%;
  #myVideo {
    width: 100%;
  }
}
</style>
